package datatransfer;

import java.util.Random;

/**
 * @author ryan
 * One example implement of the data transfer interface.
 * 
 * This naive implement use random time delay to simulate file transfer progress, and
 * considers no error happen.
 */
public class DataTransferInstance implements DataTransferInterface {
  
  /**
   * @author ryan
   * Private helper class to do the real file transfer job.
   */
  private class DataTransferInstanceHelper implements Runnable {
    private String stateString = "0%";
    private boolean isComplete = false;

    public void run() {
      /**
       * simulate file transfer progress.
       * assume that no error will happen.
       */
      stateString = "0%";
      for (int i = 0; i != 100; i++) {
        try {
          Thread.sleep(new Random().nextInt(300));
          stateString = "" + (i + 1) + "%";
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      stateString = "100%";
      isComplete = true;
    }

    public String getState() {
      return stateString;
    };

    public boolean isComplete() {
      return isComplete;
    }

    public boolean isError() {
      return false;
    }
  }
  
  public String fileName;
  public String serverUrl;
  private DataTransferInstanceHelper dhp;

  public DataTransferInstance(String fileName, String serverUrl) {}

  public void start() {
    /**
     * for period task, should support start many times
     */
    dhp = new DataTransferInstanceHelper();
    Thread t = new Thread(dhp);
    t.start();
  }

  public String getState() {
    return dhp.getState();
  };
 
  public boolean isComplete() {
    return dhp.isComplete();
  }

  public boolean isError() {
    return false;
  }

  public void suspend() {};

  public void resume() {};

}
